/**
 * User 用户支持
 * 2018年11月16日 11点27分
 * nico@coser.pub
 */
let _UR_ = require("../../script/request/user.js"); // SSR
let Context;
/** 
 * checkSuccess 验证成功
 */
function checkSuccess() {
  let visitor = wx.getStorageSync('userDetail')
  this._saveData("visitor", visitor);
}

module.exports._init = function () {
  if (!getApp()) return;
  Context  = this;
  let userStatus = getApp()._USERSTATUS_ = getApp()._USERSTATUS_ || {};
  
  this._saveData("_USER_CHECK_BUTTON_STYLE_", "top:-2rpx;position:fixed;z-index:999;" +
    "width:calc(100% + 4rpx);height:100%;padding:0;left: -2rpx;" +
    "background: linear-gradient(to bottom,rgba(0,0,0,0) 0%, rgba(0,0,0,0.3) 50% , rgba(0,0,0,0.5) 100%);" +
    "margin:0;border-radius:0;border:none;");
  let userInfoGetCallback = {
    success: function (userInfo) {
      this._saveData("_UC_/_NEED_AUTH_", false)
      userStatus.hasGotUserInfo = true;
      check.bind(this)(checkSuccess.bind(this));
    }.bind(this),
    fail: (function () {
      this._saveData("_UC_/_NEED_AUTH_", true)
    }).bind(this)
  }
  this.getUserInfoComplete = getUserInfoComplete.bind(userInfoGetCallback);

  /** 开始验证 */
  check.bind(this)(checkSuccess.bind(this));
  function check(success){
    success = success || (()=>{});
    if (!userStatus.hasBuildStory) { // 未构建本地story
      /**
       * 未构建本地story 的情况
       * @maybe 首次登入的情况
       * @maybe 删除后登入的情况
       */
      getSessionToken(getSessionTokenSuccess.bind(this));
      function getSessionTokenSuccess(session) {
        let open_id = session['openid'];
        _UR_.wxLogin({ open_id }, { success: loginSccuess.bind(this) });
        function loginSccuess(res){
          userStatus.hasBuildStory = true;
          let userDetail = res.data;
          wx.setStorageSync("userDetail", userDetail);
          check.bind(this)(success);
        }
      }
    } else if (!userStatus.hasGotUserInfo){ // 本地userInfo未定义
       /**
       * 未构建本地UserInfo 的情况
       * @maybe 首次登入的情况
       * @maybe 删除后登入的情况
       */
      let userDetail = wx.getStorageSync("userDetail");
      if (userDetail['avatar']){
        /** 若有数据，继续执行并且更新数据 */
        userStatus.hasGotUserInfo = true;
        success.bind(this)();
      }
      wx.getUserInfo({complete: getUserInfoComplete.bind(userInfoGetCallback)});
    } else success.bind(this)();
  }
}

/**
 * updateUserInfo 更新用户info
 */
function updateUserInfo(userInfo, success){
  _UR_.update({ nickname: userInfo['nickName'], avatar: userInfo['avatarUrl'] }, {
    success: function (r) {
      wx.setStorageSync('userDetail', r.data);
      (success || (() => { }))();
      (Context.onLogin || (() => { }))(Context.options);
    }.bind(this)
  });
}

/**
 * getUserInfoComplete 获取用户info成功回调
 */
function getUserInfoComplete(e) {
  let detail = e.detail || e;
  
  if (detail.errMsg == "getUserInfo:ok") {
    let userInfo = detail.userInfo;    
    wx.setStorageSync('userInfo', userInfo);
    updateUserInfo(userInfo, function(){
      this.success(userInfo);
    }.bind(this));
  } else if (detail.errMsg == "getUserInfo:fail scope unauthorized") {
    this.fail();
    function getAuthSuccess(){
      wx.getUserInfo({ complete: getUserInfoComplete.bind(this)});
    }
  }
}

/**
 * getSessionToken - 获取 Session
 * @param function successCallback 回调
 */
function getSessionToken(successCallback) {
  successCallback = successCallback|| (()=>{});
  wx.login({ success: wxLoginSuccess.bind(this) });// 发起微信登入
  /** wxLoginSuccess */
  function wxLoginSuccess(res) {
    let code = res.code;    
    _UR_.getSession({ code: code }, { success: setSession.bind(this) });//访问服务器 获取session
    /** setSession */
    function setSession(r) {
      let session = r.data
      wx.setStorageSync('tokenSession', r.data); //将session 保存在story
      successCallback.bind(this)(session);
    }
  }
}